<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

//admin用户的密码加密
function get_admin_pwd($str){
    return md5('ZSyad'.$str);
}
/**
生成订单编号
ws 特殊字符
no 序号
**/
function create_order_no($ws='o',$no=0){
    $num = 100000+$no;
    if(strlen($num) > 6){
        $s = strlen($num)-6;
        $num = substr($num,$s,strlen($num));
    }
    $rand = rand(10, 99);
    $dates=date('ymd');
    $sn = $ws.$dates.$num.$rand;
    return $sn;
}

/**请求时间**/
function now_time(){
    return $_SERVER['REQUEST_TIME'];
}

function auth_codes($str){
    $key = substr(md5('ThinkPHP.CN'), 5, 8);
    $str = substr(md5($str), 8, 10);
    return md5($key . $str);
}
/**加解密**/
function uc_authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5($key ? $key : 'jxerp');
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if($operation == 'DECODE') {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}
/***载取字符串****/
function substr_str_cut($str,$len=20,$f="..."){
    $strlen     = mb_strlen($str, 'utf-8');
    $restr = $str;
    if($strlen > $len){
        $restr = mb_substr($str, 0, $len, 'utf-8').$f;
    }
    return $restr;
}
function get_basecover_img($str){
     if(!empty($str)){
         $str=config('upload_domain').$str;
     }
     return $str;
}
function get_base_img($str){
     if(!empty($str)){
         $str=config('upload_domain').$str;
     }
     return $str;
}
function get_newpic_url($str){
    if(is_array($str)){
        $arr=array();
        foreach($str as $item){
            //$arr[]="http://oss.firebirdcj.com/".$item;
            $arr[]=config('upload_domain').$item;
        }
        $str=$arr;
     }else{
        if(!empty($str)){
            //$str="http://oss.firebirdcj.com/".$str;
            $str=config('upload_domain').$str;
        }
     }
     return $str;
}
function jsonReturn($data = '') {
    header("Content-Type:text/html; charset=utf-8");
    exit(json_encode($data,JSON_UNESCAPED_UNICODE));
}

//写日志
function write_log($log,$file=''){
    $file=empty($file)?basename(__FILE__):$file;
    $str = "";
    $str.="\r\n";
    $str.="=========================================";
    $str.="\r\n";
    $str.="POST::".$file."  time:".date('Y-m-d H:i:s');
    $str.="\r\n";
    $str.=$log;
    $str.="\r\n";
    $str.="-----------------------------------------";
    $logurl=dirname(__FILE__)."/../logs/".date('Y-m-d').".log";
    $fp = @fopen($logurl, 'ab');
    @flock($fp, LOCK_EX);
    @fwrite($fp, $str);
    @flock($fp, LOCK_UN);
    @fclose($fp);
}

/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juhecurl($url,$params=false,$ispost=0){
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}
function curl_data($url, $data='', $headers = array()){

    if(!$url || !$data) return false;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    if ($headers) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);


    curl_close($ch);
    return $response;

}
function xmlstr_to_array($xmlstr) {
  $doc = new DOMDocument();
  $doc->loadXML($xmlstr);
  $root = $doc->documentElement;
  $output = domnode_to_array($root);
  $output['root'] = $root->tagName;
  return $output;
}
function domnode_to_array($node) {
  $output = array();
  switch ($node->nodeType) {
    case XML_CDATA_SECTION_NODE:
    case XML_TEXT_NODE:
      $output = trim($node->textContent);
    break;
    case XML_ELEMENT_NODE:
      for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
        $child = $node->childNodes->item($i);
        $v = domnode_to_array($child);
        if(isset($child->tagName)) {
          $t = $child->tagName;
          if(!isset($output[$t])) {
            $output[$t] = array();
          }
          $output[$t][] = $v;
        }
        elseif($v || $v === '0') {
          $output = (string) $v;
        }
      }
      if($node->attributes->length && !is_array($output)) { //Has attributes but isn't an array
        $output = array('@content'=>$output); //Change output into an array.
      }
      if(is_array($output)) {
        if($node->attributes->length) {
          $a = array();
          foreach($node->attributes as $attrName => $attrNode) {
            $a[$attrName] = (string) $attrNode->value;
          }
          $output['@attributes'] = $a;
        }
        foreach ($output as $t => $v) {
          if(is_array($v) && count($v)==1 && $t!='@attributes') {
            $output[$t] = $v[0];
          }
        }
      }
    break;
  }
  return $output;
}
function createVerify()
{
    $rand = mt_rand(100000, 999999);
    return $rand;
}
function safe_array_entry($array, $key, $default=NULL, $unset = FALSE){
    if (($array == null) || ($key === null) || !is_array($array)) {
        return $default;
    }
    if(isset($array[$key])) {
        $value = $array[$key];
        if ($unset === FALSE) {
            unset($array[$key]);
        }
        if($value == 0)
            return strval($value);

        return $value;
    }
    return $default;
}
function is_legal_array($var){
    if (is_array($var) && count($var) >0) {
        return TRUE;
    }
    return FALSE;
}
function is_legal_string($var){
    if (is_string($var) || is_numeric($var)) {
        $var = trim($var);
        if (strlen($var) >0) {
            return TRUE;
        }
    }
    return FALSE;
}
function rand_str($length = 4, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
    {   
        $chars_length = (strlen($chars) - 1);
        $string = $chars{rand(0, $chars_length)};
        for ($i = 1; $i < $length; $i = strlen($string))
        {   
            $r = $chars{rand(0, $chars_length)};
            if ($r != $string{$i - 1}) $string .=  $r;
        }
        return $string;
    }
function getVideoInfo($video){
 $vid = "";
 //正则表达式截取vid
 preg_match_all("/(?:\/page\/)(.*)(?:\.html)/i",$video, $vid);
print_r($vid);echo "<br>";
 $vid = $vid[1][0];
 $urlString = 'https://vv.video.qq.com/getinfo?otype=json&appver=3.2.19.333&platform=11&defnpayver=1&vid='.$vid;
 $res = fopen_url($urlString);
print_r($res);echo "<br>";
 //字符串截取json
 $json = str_replace("QZOutputJson=","",$res);
 $json = str_replace("}}]}};","}}]}}",$json);
 //json转换为数组
 $json = json_decode($json,true);
 $fileName = $json['vl']['vi'][0]['fn'];
 $fvkey = $json['vl']['vi'][0]['fvkey'];
 $host = $json['vl']['vi'][0]['ul']['ui'][2]['url'];
 $url = $host.$fileName.'?vkey='.$fvkey;
 return $url;
}
/**
 获取远程文件内容
 @param $url 文件http地址
*/
function fopen_url($url)
{
 if (function_exists('file_get_contents')) {
  $file_content = @file_get_contents($url);
 } elseif (ini_get('allow_url_fopen') && ($file = @fopen($url, 'rb'))){
  $i = 0;
  while (!feof($file) && $i++ < 1000) {
   $file_content .= strtolower(fread($file, 4096));
  }
  fclose($file);
 } elseif (function_exists('curl_init')) {
  $curl_handle = curl_init();
  curl_setopt($curl_handle, CURLOPT_URL, $url);
  curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
  curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($curl_handle, CURLOPT_FAILONERROR,1);
  curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Trackback Spam Check'); //引用垃圾邮件检查
  $file_content = curl_exec($curl_handle);
  curl_close($curl_handle);
 } else {
  $file_content = '';
 }
 return $file_content;
}
